<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MyServer</title>
    <link rel="icon" th:href="@{/favicon.png}" type="image/png"/>
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" th:href="@{/css/Game.css}">
</head>
<body>
<div id="app">
    <!-- 顶部导航栏 -->
    <header class="header">
        <button class="back-btn" @click="goToHome">返回主页面</button>
        <button v-if="!BGMStart" class="back-btn" @click="BGMSet">开启BGM</button>
        <button v-else class="back-btn" @click="BGMSet">关闭BGM</button>
        <audio id="bgm" loop preload="metadata">
            <source src="/BGM.wav" type="audio/wav">
        </audio>
        <div class="user-info">
            <div class="user-avatar">
                <img v-if="user.avatar" :src="user.avatar" alt="头像" class="avatar" @click="goToUserProfile" title="点击进入用户管理">
                <span v-else>{{ userInitial }}</span>
            </div>
            <div class="username">{{ user.username || '玩家' }}</div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
        <!-- 资源状态显示 -->
        <h2 class="section-title">服务器资源状态</h2>
        <div class="resource-container">
            <div class="resource-card">
                <div class="resource-label">资金</div>
                <div class="resource-value">{{ gameData.gold || 0 }}</div>
            </div>
            <div class="resource-card">
                <div class="resource-label">行动点</div>
                <div class="resource-value">{{ gameData.actionPoint || 0 }}</div>
            </div>
            <div class="resource-card">
                <div class="resource-label">风评</div>
                <div class="resource-value">{{ gameData.reputation ? gameData.reputation.toFixed(1) : 0.0 }}</div>
            </div>
            <div class="resource-card">
                <div class="resource-label">人流</div>
                <div class="resource-value">{{ gameData.traffic || 0 }}</div>
            </div>
            <div class="resource-card">
                <div class="resource-label">人均消费</div>
                <div class="resource-value">{{ gameData.avgConsumption ? gameData.avgConsumption.toFixed(1) : 0.0 }}</div>
            </div>
            <div class="resource-card">
                <div class="resource-label">回合</div>
                <div class="resource-value">{{ gameData.turns || 0 }}</div>
            </div>
            <div v-if="gameData.stage >= 3" class="resource-card">
                <div class="resource-label">宣发力度</div>
                <div class="resource-value">{{ promotionCost || 0 }}</div>
            </div>
            <div class="resource-card">
                <div class="resource-label">阶段</div>
                <div class="resource-value">阶段 {{ gameData.stage || 1 }}</div>
            </div>
        </div>

        <!-- 功能模块区 -->
        <h2 class="section-title">服务器功能模块</h2>
        <div class="modules-container">
            <div class="module-card" @click="openModule('front')">
                <div class="module-icon">🖥️</div>
                <div class="module-name">前端</div>
                <div class="module-status">平均等级: {{ moduleAvgLevels.front }}</div>
            </div>
            <div class="module-card" @click="openModule('back')">
                <div class="module-icon">⚙️</div>
                <div class="module-name">后端</div>
                <div class="module-status">评价等级: {{ moduleAvgLevels.back }}</div>
            </div>
            <div class="module-card" @click="openModule('hr')">
                <div class="module-icon">👥</div>
                <div class="module-name">人力</div>
                <div class="module-status">人力资源: {{ gameData.humanResources ? gameData.humanResources.length : 0 }}</div>
            </div>
<!--            @click="openModule('project')"-->
            <div class="module-card" @click="openGuide">
                <div class="module-icon">🧭</div>
                <div class="module-name">指南</div>
                <div class="module-status">不懂怎么玩就来这里看看</div>
            </div>
            <div class="module-card" :class="{'locked-module': gameData.stage < 2}" @click="gameData.stage >= 2 && openModule('security')">
                <div class="module-icon">🔐</div>
                <div class="module-name">安全</div>
                <div class="module-status" v-if="gameData.stage >= 2">平均等级: {{ moduleAvgLevels.security }}</div>
                <div class="module-status" v-else>阶段2解锁</div>
            </div>
            <div class="module-card" :class="{'locked-module': gameData.stage < 3}" @click="gameData.stage >= 3 && openModule('promotion')">
                <div class="module-icon">📢</div>
                <div class="module-name">宣发</div>
                <div class="module-status" v-if="gameData.stage >= 3">可用</div>
                <div class="module-status" v-else>阶段3解锁</div>
            </div>
        </div>

        <!-- 操作按钮区 -->
        <div class="actions-container">
            <button class="action-btn end-turn-btn" @click="endTurn">结束当前回合</button>
            <button class="action-btn upgrade-stage-btn" :class="{'disabled-btn': !canUpgradeStage}" @click="upgradeStage">阶段升级</button>
        </div>
    </main>

    <!-- 底部版权 -->
    <footer class="footer">
        Copyright &copy; 2025 Wooming Games. 版权所有。
    </footer>

    <!-- 新增：模块悬浮窗 -->
    <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>{{ currentModule.title }}模块</h3>
                <button @click="closeModal" class="close-btn">×</button>
            </div>

            <div class="module-details">
                <div v-for="subModule in currentModule.subModules" :key="subModule.name" class="sub-module-card">
                    <div class="sub-module-info">
                        <h4>{{ subModule.displayName }}</h4>
                        <p>当前等级: {{ subModule.currentLevel }}</p>
                        <p>功能描述: {{ subModule.description }}</p>
                    </div>
                    <div class="upgrade-section">
                        <p>升级消耗: {{ subModule.upgradeCost.gold }}资金, {{ subModule.upgradeCost.action }}行动点</p>
                        <button
                                @click="upgradeModule(subModule.name)"
                                :disabled="!canUpgrade(subModule)"
                                class="upgrade-btn"
                        >
                            升级
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增：宣发模块悬浮窗 -->
    <div v-if="showPromotionModal" class="modal-overlay" @click.self="closePromotionModal">
        <div class="modal-content promotion-modal">
            <div class="modal-header">
                <h3>宣发活动</h3>
                <P>根据花费,按比例提高影响倍率</P>
                <button @click="closePromotionModal" class="close-btn">×</button>
            </div>

            <div class="promotion-options">
                <div class="promotion-option" v-for="option in promotionOptions" :key="option.id">
                    <h4>{{ option.name }}</h4>
                    <p>{{ option.description }}</p>
                    <p>消耗: {{ option.cost }}资金</p>
                    <button
                            @click="launchPromotion(option)"
                            :disabled="gameData.gold < option.cost"
                            class="promotion-btn"
                    >
                        启动宣发
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增人力模块抽屉 -->
    <div class="drawer" :class="{ 'drawer-open': showHumanDrawer }">
        <div class="drawer-header">
            <h3>人力资源</h3>
            <button @click="showHumanDrawer = false" class="close-btn">×</button>
        </div>

        <!-- 招募按钮区域 -->
        <div class="recruit-section">
            <button
                    @click="openRecruitment"
                    :disabled="gameData.gold < recruitCost"
                    class="recruit-btn"
            >
                招募人员 ({{ recruitCost }}资金)
            </button>
            <p v-if="gameData.gold < recruitCost" class="insufficient-funds">
                资金不足！需要至少{{ recruitCost}}资金
            </p>
        </div>

        <!-- 人力列表 -->
        <div class="human-list">
            <div v-for="(human, index) in gameData.humanResources" :key="human.id" class="human-card">
                <div class="human-info">
                    <h4>{{ human.name }}</h4>
                    <div class="human-stats">
                        <p>等级: {{ human.level }}/{{ human.maxLevel }}</p>
                        <p>行动点: +{{ human.actionPoint }}/级</p>
                        <p>薪水: {{ human.salary }}/级</p>
                        <p>训练花费: {{ human.trainCost }}</p>
                    </div>
                </div>
                <button
                        v-if="human.level < human.maxLevel"
                        @click="upgradeHuman(index)"
                        :disabled="gameData.gold < human.trainCost"
                        class="upgrade-btn"
                >
                    升级
                </button>
                <button
                        v-if="human.level >= human.maxLevel"
                        :disabled= "true"
                        class="upgrade-btn"
                >
                    已满级
                </button>
            </div>
        </div>
    </div>

    <!-- 招募悬浮窗 -->
    <div v-if="showRecruitmentModal" class="modal-overlay" @click.self="closeRecruitmentModal">
        <div class="modal-content recruitment-modal">
            <div class="modal-header">
                <h3>招募新成员</h3>
                <button @click="closeRecruitmentModal" class="close-btn">×</button>
            </div>

            <div class="candidates-container">
                <div
                        v-for="(candidate, index) in recruitmentCandidates"
                        :key="index"
                        :class="['candidate-card', { selected: selectedCandidateIndex === index }]"
                        @click="selectCandidate(index)"
                >
                    <div class="candidate-info">
                        <h4>{{ candidate.name }}</h4>
                        <p>等级: {{ candidate.level }}/{{ candidate.maxLevel }}</p>
                        <p>行动点: +{{ candidate.actionPoint }}/级</p>
                        <p>薪水: {{ candidate.salary }}/级</p>
                        <p>训练花费: {{ candidate.trainCost }}</p>
                    </div>
                </div>
            </div>

            <div class="recruitment-actions">
                <button @click="closeRecruitmentModal" class="cancel-btn">取消招募</button>
                <label>
                    <input class="candidate-name-input" type="text" v-model="candidateName" placeholder="输入成员名称">
                </label>
                <button
                        @click="confirmRecruitment"
                        :disabled="selectedCandidateIndex === null"
                        class="confirm-btn"
                >
                    确认招募
                </button>
            </div>
        </div>
    </div>

    <!-- 新增回合结算悬浮窗 -->
    <div v-if="showTurnResultModal" class="modal-overlay" @click.self="closeTurnResultModal">
        <div class="modal-content turn-result-modal">
            <div class="modal-header">
                <h3>回合结算报告 (回合 {{ gameData.turns }})</h3>
                <button @click="closeTurnResultModal" class="close-btn">×</button>
            </div>

            <div class="turn-result-content">
                <!-- 7个结算周期详细信息 -->
                <h4 class="section-subtitle">结算周期详情</h4>
                <div class="cycles-container">
                    <div v-for="(cycle, index) in turnResult.cyclesData" :key="index" class="cycle-card">
                        <div class="cycle-header">
                            <div class="cycle-rank">周期 {{ cycle.rank }}</div>
                            <div class="cycle-events">
                                <!-- 显示该周期发生的事件 -->
                                <span v-for="(event, eventIndex) in getCycleEvents(cycle.rank)"
                                      :key="eventIndex"
                                      class="event-tag"
                                      :style="{ backgroundColor: getEventColor(event), color: '#0f172a' }">
                                {{ getEventIcon(event) }} {{ mapEventName(event) }}
                            </span>
                            </div>
                        </div>
                        <div class="cycle-stats">
                            <div class="cycle-stat">
                                <div class="stat-label">营收</div>
                                <div class="stat-value">{{ cycle.goldGet }}</div>
                            </div>
                            <div class="cycle-stat">
                                <div class="stat-label">人流变化</div>
                                <div class="stat-value">{{ cycle.trafficChange }}</div>
                            </div>
                            <div class="cycle-stat">
                                <div class="stat-label">人均消费变化</div>
                                <div class="stat-value">{{ cycle.avgConsumptionChange.toFixed(1) }}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 回合总结数据 -->
                <h4 class="section-subtitle">回合总结</h4>
                <div class="turn-summary">
                    <div class="summary-item">
                        <div class="summary-label">总开销</div>
                        <div class="summary-value negative">{{ turnResult.totalGoldCost }}</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-label">总营收</div>
                        <div class="summary-value positive">{{ turnResult.totalGoldGet }}</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-label">总人流变化</div>
                        <div class="summary-value" :class="{ positive: turnResult.totalTrafficChange > 0, negative: turnResult.totalTrafficChange < 0 }">
                            {{ turnResult.totalTrafficChange }}
                        </div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-label">人均消费变化</div>
                        <div class="summary-value" :class="{ positive: turnResult.totalAvgConsumptionChange > 0, negative: turnResult.totalAvgConsumptionChange < 0 }">
                            {{ turnResult.totalAvgConsumptionChange.toFixed(1) }}
                        </div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-label">风评变化</div>
                        <div class="summary-value" :class="{ positive: turnResult.reputationChange > 0, negative: turnResult.reputationChange < 0 }">
                            {{ turnResult.reputationChange.toFixed(1) }}
                        </div>
                    </div>
                </div>
            </div>

            <div class="turn-result-footer">
                <button @click="closeTurnResultModal" class="action-btn confirm-btn">确认</button>
            </div>
        </div>
    </div>

    <!-- 游戏指南悬浮窗 -->
    <div v-if="showGuideModal" class="modal-overlay guide-overlay" @click.self="closeGuide">
        <div class="modal-content guide-modal">
            <div class="modal-header">
                <h3>《My Server》游戏指南</h3>
                <button @click="closeGuide" class="close-btn">×</button>
            </div>

            <div class="guide-container">
                <!-- 左侧目录导航 -->
                <div class="guide-nav">
                    <div class="nav-header">目录导航</div>
                    <ul class="nav-list">
                        <li v-for="section in guideContent" :key="section.id"
                            :class="{ active: currentSection === section.id }"
                            @click="scrollToSection(section.id)">
                            {{ section.title }}
                        </li>
                    </ul>
                </div>

                <!-- 右侧内容区域 -->
                <div class="guide-content">
                    <div v-for="section in guideContent" :key="section.id" :id="section.id" class="guide-section">
                        <h4 class="section-title">{{ section.title }}</h4>
                        <div class="section-content" v-html="section.content"></div>
                    </div>
                </div>
            </div>

            <div class="guide-footer">
                <button @click="closeGuide" class="action-btn confirm-btn">关闭指南</button>
            </div>
        </div>
    </div>
</div>

<script>
    const { createApp } = Vue;

    createApp({
        data() {
            return {
                user: {
                    username: '',
                    avatar: ''
                },
                gameData: {
                    gold: 0,
                    actionPoint: 0,
                    reputation: 0,
                    traffic: 0,
                    avgConsumption: 0,
                    turns: 0,
                    stage: 1,
                    humanResources: [],
                    moduleStatuses: []
                },
                moduleAvgLevels: {
                    front : 0,
                    back : 0,
                    security: 0
                },
                upgradeCosts: {},  // 升级成本数据暂存
                canUpgradeStage: false,
                BGMStart: false,
                // 新增悬浮窗相关数据
                showModal: false,
                showPromotionModal: false,
                currentModule: null,
                promotionCost: 0, // 宣发花费
                showHumanDrawer: false,
                showRecruitmentModal: false,
                recruitmentCandidates: [],
                candidateName: '',
                selectedCandidateIndex: null,
                recruitCost: 0,
                recruitCostBase: 1000, // 生成人员花费
                recruitCostIncrement: [3000, 10000, 50000], // 招募成本递增数组
                // 阶段升级成本
                stageUpNeedGold: [50000, 150000],
                stageUpNeedAction: [100, 250],
                stageUpNeedTraffic: [500, 1000],
                stageUpNeedTurn: [10, 20],
                stageUpCostGold: [10000, 100000],
                stageUpCostAction: [50, 200],
                // 模块数据（示例）
                modules: {
                    front: {
                        title: "前端",
                        subModules: [
                            {
                                name: "Front.UI",
                                displayName: "用户界面",
                                currentLevel: 1,
                                description: "负责用户界面的设计和实现,每级提高下一回合风评",
                                upgradeCost: { gold: 100, action: 10 }
                            },
                            {
                                name: "Front.Interact",
                                displayName: "交互逻辑",
                                currentLevel: 1,
                                description: "处理用户交互和响应,每级提高一些人流量",
                                upgradeCost: { gold: 120, action: 15 }
                            },
                            {
                                name: "Front.Framework",
                                displayName: "前端架构",
                                currentLevel: 1,
                                description: "整体前端架构设计,每级减少全部前端升级花费",
                                upgradeCost: { gold: 200, action: 25 }
                            }
                        ]
                    },
                    back: {
                        title: "后端",
                        subModules: [
                            {
                                name: "Back.Speed",
                                displayName: "响应速度",
                                currentLevel: 1,
                                description: "服务器响应速度优化,每级提高下一回合风评",
                                upgradeCost: { gold: 150, action: 20 }
                            },
                            {
                                name: "Back.Comm",
                                displayName: "通讯协议",
                                currentLevel: 1,
                                description: "数据传输协议优化,每级提高人均消费水平",
                                upgradeCost: { gold: 130, action: 15 }
                            },
                            {
                                name: "Back.Framework",
                                displayName: "后端架构",
                                currentLevel: 1,
                                description: "整体后端架构设计,每级减少后端和安全模块升级花费",
                                upgradeCost: { gold: 250, action: 30 }
                            }
                        ]
                    },
                    security: {
                        title: "安全",
                        subModules: [
                            {
                                name: "Security.DDoS",
                                displayName: "DDoS防护",
                                currentLevel: 1,
                                description: "分布式拒绝服务攻击防护,降低DDoS受击风险",
                                upgradeCost: { gold: 200, action: 25 }
                            },
                            {
                                name: "Security.SQL",
                                displayName: "SQL注入防护",
                                currentLevel: 1,
                                description: "数据库安全防护,降低SQL注入受击风险",
                                upgradeCost: { gold: 180, action: 20 }
                            },
                            {
                                name: "Security.XSS",
                                displayName: "XSS防护",
                                currentLevel: 1,
                                description: "跨站脚本攻击防护,降低XXS受击风险",
                                upgradeCost: { gold: 170, action: 18 }
                            }
                        ]
                    }
                },
                // 宣发选项
                promotionOptions: [
                    {
                        id: 1,
                        name: "社交媒体推广",
                        description: "在主流社交媒体平台进行推广",
                        cost: 50000
                    },
                    {
                        id: 2,
                        name: "搜索引擎优化",
                        description: "优化网站SEO提升搜索排名",
                        cost: 100000
                    },
                    {
                        id: 3,
                        name: "广告投放",
                        description: "在相关网站投放广告",
                        cost: 250000
                    }
                ],
                // 回合结算
                showTurnResultModal: false,
                turnResult: {
                    event: [],
                    happenedRank: [],
                    cyclesData: [],
                    totalGoldCost: 0,
                    totalGoldGet: 0,
                    totalTrafficChange: 0,
                    totalAvgConsumptionChange: 0,
                    reputationChange: 0,
                    gameData:{}
                },
                showGuideModal: false,
                guideContent: [
                    {
                        id: "intro",
                        title: "游戏介绍",
                        content: "《My Server》是一款模拟服务器运营的策略游戏，玩家需要管理服务器资源、升级模块、招募人才，不断提升服务器性能和市场竞争力。"
                    },
                    {
                        id: "stages",
                        title: "发展阶段",
                        content: `
            <p>游戏分为三个主要发展阶段：</p>
            <ul>
                <li><span class="highlight-blue">阶段1</span>：基础建设期，关注服务器基础模块搭建</li>
                <li><span class="highlight-orange">阶段2</span>：安全防护期，解锁安全模块增强防御能力</li>
                <li><span class="highlight-purple">阶段3</span>：市场扩展期，解锁宣发功能扩大影响力</li>
            </ul>
            <ul>
                <li><span class="highlight-orange">阶段2升级需求</span>:资金存量>50000;行动点>100;人流量>500;回合数>10</li>
                <li><span class="highlight-purple">阶段3升级需求</span>:资金存量>150000;行动点>250;人流量>1000;回合数>20</li>
                <li><span class="highlight-red">注:升级阶段需要消耗一定资源,但不是全部</span></li>
            </ul>
        `
                    },
                    {
                        id: "resources",
                        title: "资源系统",
                        content: `
            <p>游戏中有五种核心资源：</p>
            <div class="resource-list">
                <div class="resource-item highlight-gold">💰 <strong>资金</strong> - 服务器运营基础货币,这是最基本的资源</div>
                <div class="resource-item highlight-green">⚡ <strong>行动点</strong> - 执行操作所需点数,这种资源没回合刷新一次,没使用完的会在下一回合转变为资金</div>
                <div class="resource-item highlight-red">📊 <strong>风评</strong> - 用户对服务器的评价,这会成比例影响到下一回合结算时所有变化</div>
                <div class="resource-item highlight-blue">👥 <strong>人流</strong> - 访问服务器的用户量,乘以消费水平决定一周期内的基本营收</div>
                <div class="resource-item highlight-purple">💳 <strong>人均消费</strong> - 用户平均消费水平,乘以人流量决定一周期内的基本营收</div>
            </div>
        `
                    },
                    {
                        id: "modules",
                        title: "功能模块",
                        content: `
            <p>服务器包含五大功能模块：</p>
            <div class="module-card">
                <div class="module-icon">🖥️</div>
                <div class="module-info">
                    <h4>前端模块</h4>
                    <p>提升用户界面体验，影响风评和人流量</p>
                    <ul>
                        <li>用户界面(UI) - 每回合提升风评</li>
                        <li>交互逻辑(Interact) - 每回合提高人流量</li>
                        <li>前端架构(Framework) - 减少前端升级成本</li>
                    </ul>
                </div>
            </div>
            <!-- 其他模块类似结构 -->
            <div class="module-card">
                <div class="module-icon">⚙️</div>
                <div class="module-info">
                    <h4>后端模块</h4>
                    <p>提升业务处理能力，影响风评和人均消费水平</p>
                    <ul>
                        <li>响应速度(Speed) - 每回合提升风评</li>
                        <li>通讯协议(Comm) - 每回合提高人均消费水平</li>
                        <li>后端架构(Framework) - 减少后端与安全模块升级成本</li>
                    </ul>
                </div>
            </div>
            <div class="module-card">
                <div class="module-icon">👥</div>
                <div class="module-info">
                    <h4>人力模块</h4>
                    <p>招募人才,获取额外行动点</p>
                    <ul>
                        <li><strong>这是本游戏行动点增加的唯一途径!</strong></li>
                        <li>招募人力时记得为ta取名,由于设计缺陷,暂时无法改名,因此取名请谨慎</li>
                        <li>招募前生成人力固定消耗1000资金,确定招募是又会消耗一定资金进行确认</li>
                        <li>人力的产出与消耗均与等级挂钩,升级时请注意</li>
                    </ul>
                </div>
            </div>
            <div class="module-card">
                <div class="module-icon">🔐</div>
                <div class="module-info">
                    <h4>安全模块</h4>
                    <p>降低受击风险</p>
                    <ul>
                        <li>DDoS防护 - 降低DDoS受击风险</li>
                        <li>SQL注入防护 - 降低SQL注入受击风险</li>
                        <li>XXS防护 - 降低XXS受击风险</li>
                    </ul>
                </div>
            </div>
            <div class="module-card">
                <div class="module-icon">📢</div>
                <div class="module-info">
                    <h4>宣发模块</h4>
                    <p>花费资金,提高影响倍率</p>
                    <ul>
                        <li><strong>不必过分关注宣发活动类型,后端只计算资金消耗.</strong></li>
                    </ul>
                </div>
            </div>
        `
                    },
                    {
                        id: "turns",
                        title: "回合系统",
                        content: `
            <p>游戏以回合为单位进行：</p>
            <ol>
                <li>每个回合包含<span class="highlight-blue">7个结算周期</span>,每个结算周期单独计算,在统计回合总计变化</li>
                <li>每个周期可能发生事件影响资源变化,详见事件系统</li>
                <li>每个资源结算均有浮动值影响,这个需要看一定的运气</li>
                <li>完成必要升级后可进入下一阶段</li>
            </ol>
        `
                    },
                    {
                        id: "events",
                        title: "事件系统",
                        content: `
            <p>每个回合可能发生以下事件：</p>
            <div class="tip-box">
                <h4>攻击事件</h4>
                <p><span class="highlight-red">DDoS攻击</span>: 受击后使受击周期及以后均无营收</p>
                <p><span class="highlight-red">SQL注入攻击</span>: 受击后使受击营收减半,人流降低</p>
                <p><span class="highlight-red">XSS攻击</span>: 受击后各资源变化均减少</p>
                <h4>其他事件</h4>
                <p><span class="highlight-blue">受关注</span>: 提高人流量变化与人均消费变化</p>
                <p><span class="highlight-gold">风口</span>: 大幅提高营收</p>
                <h4>相关概率</h4>
                <p><span class="highlight-orange">受击优先级:DDoS > SQL > XSS</span>,各受击事件触发概率随回合数增加而增加,随人流增减而增加,随对应安全模块等级增加而减小</p>
                <p><span class="highlight-orange">其他事件优先级:受关注 > 风口</span>,概率固定为10%</p>
                <p><span class="highlight-purple">两种事件可在同一回合内触发</span>.</p>
            </div>
        `
                    },
                    {
                        id: "strategies",
                        title: "进阶策略",
                        content: `
            <p>部分建议：</p>
            <div class="tip-box">
                <p>💡 <span class="highlight-green">均衡发展</span>：不要过度偏重单一模块</p>
                <p>💡 <span class="highlight-orange">人才投资</span>：早期招募人员回报丰厚</p>
                <p>💡 <span class="highlight-purple">风险防范</span>：安全模块升级避免后期损失</p>
                <p>💡 <span class="highlight-blue">宣发时机</span>：阶段3后合理使用宣发活动</p>
            </div>
        `
                    }
                ],
                currentSection: "intro" // 当前选中的部分
            }
        },
        computed: {
            // 获取用户名的首字母用于头像显示
            userInitial() {
                return this.user.username ? this.user.username.charAt(0).toUpperCase() : 'P';
            },
            // 计算显示的资金（原始资金减去宣发花费）
            displayGold() {
                return this.gameData.gold - this.promotionCost;
            }
        },
        mounted() {
            this.checkAuthAndInitialize();
        },
        methods: {
            // 检查认证并初始化游戏
            checkAuthAndInitialize() {
                const jwt = localStorage.getItem('jwt');
                if (!jwt) {
                    this.redirectToLogin();
                    return;
                }

                // 验证JWT并获取用户信息
                axios.post('/api/public/verify', {
                    jwt: jwt
                })
                    .then(response => {
                        this.user.username = localStorage.getItem('username');

                        // 获取用户头像
                        return axios.get('/api/headshot', {
                            headers: { 'Authorization': `Bearer ${jwt}` },
                            responseType: 'blob'
                        });
                    })
                    .then(avatarResponse => {
                        const blob = new Blob([avatarResponse.data], { type: avatarResponse.headers['content-type'] });
                        this.user.avatar = URL.createObjectURL(blob);

                        // 开始游戏
                        return axios.get('/api/game/start', {
                            headers: { 'Authorization': `Bearer ${jwt}` }
                        });
                    })
                    .then(gameResponse => {
                        this.gameData = gameResponse.data.data;

                        // 更改显示
                        this.modules.front.subModules[0].currentLevel = this.gameData.moduleStatuses.filter(m => m.moduleType === 'Front.UI')[0].currentLevel;
                        this.modules.front.subModules[1].currentLevel = this.gameData.moduleStatuses.filter(m => m.moduleType === 'Front.Interact')[0].currentLevel;
                        this.modules.front.subModules[2].currentLevel = this.gameData.moduleStatuses.filter(m => m.moduleType === 'Front.Framework')[0].currentLevel;

                        this.modules.back.subModules[0].currentLevel = this.gameData.moduleStatuses.filter(m => m.moduleType === 'Back.Speed')[0].currentLevel;
                        this.modules.back.subModules[1].currentLevel = this.gameData.moduleStatuses.filter(m => m.moduleType === 'Back.Comm')[0].currentLevel;
                        this.modules.back.subModules[2].currentLevel = this.gameData.moduleStatuses.filter(m => m.moduleType === 'Back.Framework')[0].currentLevel;

                        this.modules.security.subModules[0].currentLevel = this.gameData.moduleStatuses.filter(m => m.moduleType === 'Security.DDoS')[0].currentLevel;
                        this.modules.security.subModules[1].currentLevel = this.gameData.moduleStatuses.filter(m => m.moduleType === 'Security.SQL')[0].currentLevel;
                        this.modules.security.subModules[2].currentLevel = this.gameData.moduleStatuses.filter(m => m.moduleType === 'Security.XSS')[0].currentLevel;
                        // 获取所有模块升级消耗
                        this.getAllUpgradeCosts();

                        // 更新招募花费
                        this.recruitCost = this.recruitCostBase + this.recruitCostIncrement[this.gameData.stage - 1]

                        // 更新平均等级
                        this.moduleAvgLevels.front = this.getModuleLevel('Front')
                        this.moduleAvgLevels.back = this.getModuleLevel('Back')
                        this.moduleAvgLevels.security = this.getModuleLevel('Security')
                    })
                    .catch(error => {
                        console.error('初始化失败:', error);
                        this.redirectToLogin();
                    });
            },

            // 检查是否可以升级阶段
            checkStageUpgrade() {
                if (this.stage === 3) {
                    this.canUpgradeStage = false;
                } else {
                    this.canUpgradeStage = this.gameData.gold >= this.stageUpNeedGold[this.gameData.stage - 1] &&
                        this.gameData.actionPoint >= this.stageUpNeedAction[this.gameData.stage - 1] &&
                        this.gameData.traffic >= this.stageUpNeedTraffic[this.gameData.stage - 1] &&
                        this.gameData.turns >= this.stageUpNeedTurn[this.gameData.stage - 1];
                    if (!this.canUpgradeStage) {
                        if (this.gameData.gold < this.stageUpNeedGold[this.gameData.stage - 1]) alert('资金储量不足')
                        if (this.gameData.actionPoint < this.stageUpNeedAction[this.gameData.stage - 1]) alert('行动点储量不足')
                        if (this.gameData.traffic < this.stageUpNeedTraffic[this.gameData.stage - 1]) alert('人流量不足')
                        if (this.gameData.turns < this.stageUpNeedTurn[this.gameData.stage - 1]) alert('回合数不足')
                    }
                }
            },

            // 跳转到登录页
            redirectToLogin() {
                window.location.href = '/user';
            },

            // 返回主页面
            goToHome() {
                window.location.href = '/';
            },

            // 用户管理界面
            goToUserProfile() {
                window.location.href = '/userProfile';
            },

            // BGM控制
            BGMSet() {
                if(!this.BGMStart){
                    document.getElementById('bgm').play();
                    this.BGMStart = true;
                } else {
                    document.getElementById('bgm').pause();
                    this.BGMStart = false;
                }
            },

            // 升级阶段
            upgradeStage() {
                // 检查是否可以升级阶段
                this.checkStageUpgrade();
                if (!this.canUpgradeStage) return;

                axios.post('/api/game/stageUp', {}, {
                    headers: { 'Authorization': `Bearer ${localStorage.getItem('jwt')}` }
                })
                    .then(response => {
                        if (response.data.code === 200) {
                            localStorage.setItem('jwt', response.data.data);
                            // 更新招募花费
                            this.recruitCost = this.recruitCostBase + this.recruitCostIncrement[this.gameData.stage - 1]
                            // 更新阶段
                            this.gameData.stage += 1
                            // 更新人力
                            return axios.get('api/hr/get',{
                                headers: { 'Authorization': `Bearer ${localStorage.getItem('jwt')}` }
                            })
                        } else {
                            alert(response.data.message);
                        }
                    })
                    .then(response => {
                        // 更新人力
                        this.gameData.humanResources = response.data.data;
                        // 提示
                        alert(`成功升级到阶段 ${this.gameData.stage}！`);
                    })
                    .catch(error => {
                        console.error('升级阶段失败:', error);
                        alert('升级阶段失败，请检查条件');
                    });
            },

            // 新增方法：打开模块
            openModule(moduleType) {
                if (moduleType === 'promotion') {
                    this.showPromotionModal = true;
                } else if (moduleType === 'hr'){
                    this.openHumanDrawer()
                } else {
                    this.currentModule = this.modules[moduleType];
                    this.showModal = true;
                }
            },

            // 关闭模块悬浮窗
            closeModal() {
                this.showModal = false;
                this.currentModule = null;
            },

            // 关闭宣发悬浮窗
            closePromotionModal() {
                this.showPromotionModal = false;
            },

            // 检查是否可以升级
            canUpgrade(subModule) {
                return this.gameData.gold >= subModule.upgradeCost.gold &&
                    this.gameData.actionPoint >= subModule.upgradeCost.action;
            },

            // 升级模块
            upgradeModule(moduleName) {
                const jwt = localStorage.getItem('jwt');
                if (!jwt) {
                    this.redirectToLogin();
                    return;
                }

                // 发送升级请求
                axios.post('/api/game/levelUp', {}, {
                    params: { moduleName },
                    headers: { 'Authorization': `Bearer ${jwt}` }
                })
                    .then(response => {
                        const costVO = response.data.data;

                        // 更新模块等级
                        const module = this.currentModule.subModules.find(m => m.name === moduleName);
                        if (module) {
                            module.currentLevel++;
                            this.gameData.moduleStatuses.filter(m => m.moduleType === moduleName)[0].currentLevel++;

                            // 更新资源
                            this.gameData.gold -= module.upgradeCost.gold;
                            this.gameData.actionPoint -= module.upgradeCost.action;

                            // 更新消耗信息
                            module.upgradeCost = {
                                gold: costVO.gold,
                                action: costVO.action
                            };

                            // 如果是架构模块，重新获取所有模块升级消耗
                            if (moduleName === 'Front.Framework' || moduleName === 'Back.Framework') {
                                this.getAllUpgradeCosts();
                            }

                            // 更新模块平均等级
                            this.moduleAvgLevels.front = this.getModuleLevel('Front')
                            this.moduleAvgLevels.back = this.getModuleLevel('Back')
                            this.moduleAvgLevels.security = this.getModuleLevel('Security')

                            alert(`${module.displayName} 升级成功！当前等级: ${module.currentLevel}`);
                        }
                    })
                    .catch(error => {
                        console.error('升级失败:', error);
                        alert('升级失败，请检查资源是否充足');
                    });
            },

            // 获取模块等级（根据模块类型前缀）
            getModuleLevel(modulePrefix) {
                if (!this.gameData.moduleStatuses) return 0;

                const modules = this.gameData.moduleStatuses.filter(
                    m => m.moduleType.startsWith(modulePrefix)
                );

                if (modules.length === 0) return 0;

                // 计算平均等级
                const totalLevel = modules.reduce((sum, m) => sum + m.currentLevel, 0);
                return (totalLevel / modules.length).toFixed(1);
            },

            // 获取所有模块升级消耗（第一阶段已有）
            getAllUpgradeCosts() {
                // 实现代码同第一阶段
                axios.get('/api/game/cost', {
                    headers: { 'Authorization': 'Bearer ' + localStorage.getItem('jwt')}
                }).then(response => {
                    this.upgradeCosts = response.data.data;

                    // 显示升级花费
                    this.modules.front.subModules[0].upgradeCost.gold = this.upgradeCosts.frontUIGold
                    this.modules.front.subModules[1].upgradeCost.gold = this.upgradeCosts.frontInteractGold
                    this.modules.front.subModules[2].upgradeCost.gold = this.upgradeCosts.frontFrameworkGold
                    this.modules.back.subModules[0].upgradeCost.gold = this.upgradeCosts.backSpeedGold
                    this.modules.back.subModules[1].upgradeCost.gold = this.upgradeCosts.backCommGold
                    this.modules.back.subModules[2].upgradeCost.gold = this.upgradeCosts.backFrameworkGold
                    this.modules.security.subModules[0].upgradeCost.gold = this.upgradeCosts.securityDDoSGold
                    this.modules.security.subModules[1].upgradeCost.gold = this.upgradeCosts.securitySQLGold
                    this.modules.security.subModules[2].upgradeCost.gold = this.upgradeCosts.securityXSSGold
                    this.modules.front.subModules[0].upgradeCost.action = this.upgradeCosts.frontUIAction
                    this.modules.front.subModules[1].upgradeCost.action = this.upgradeCosts.frontInteractAction
                    this.modules.front.subModules[2].upgradeCost.action = this.upgradeCosts.frontFrameworkAction
                    this.modules.back.subModules[0].upgradeCost.action = this.upgradeCosts.backSpeedAction
                    this.modules.back.subModules[1].upgradeCost.action = this.upgradeCosts.backCommAction
                    this.modules.back.subModules[2].upgradeCost.action = this.upgradeCosts.backFrameworkAction
                    this.modules.security.subModules[0].upgradeCost.action = this.upgradeCosts.securityDDoSAction
                    this.modules.security.subModules[1].upgradeCost.action = this.upgradeCosts.securitySQLAction
                    this.modules.security.subModules[2].upgradeCost.action = this.upgradeCosts.securityXSSAction
                })
            },

            // 启动宣发活动
            launchPromotion(option) {
                // 暂存宣发花费
                this.promotionCost += option.cost;
                this.gameData.gold -= option.cost;

                // 更新显示资金（计算属性已处理）
                alert(`已启动 "${option.name}" 宣发活动，花费 ${option.cost} 金币`);

                // // 关闭宣发窗口
                // this.closePromotionModal();
            },

            // 打开人力抽屉
            openHumanDrawer() {
                this.showHumanDrawer = true;
            },

            // 打开招募悬浮窗
            openRecruitment() {
                if (this.gameData.gold < this.recruitCost) return;

                // 模拟从后端获取候选人
                this.getRecruitmentCandidates();
                this.showRecruitmentModal = true;
                this.selectedCandidateIndex = null;
            },

            // 关闭招募悬浮窗
            closeRecruitmentModal() {
                this.showRecruitmentModal = false;
                this.recruitmentCandidates = [];
            },

            // 获取招募候选人（模拟后端请求）
            getRecruitmentCandidates() {
                this.gameData.gold -= this.recruitCostBase;

                // 实际应使用axios请求后端API
                axios.get('/api/hr/random',{
                    headers: { 'Authorization': 'Bearer ' + localStorage.getItem('jwt')}
                })
                  .then(response => {
                    this.recruitmentCandidates = response.data.data;
                  });
            },

            // 选择候选人
            selectCandidate(index) {
                this.selectedCandidateIndex = index;
            },

            // 确认招募
            confirmRecruitment() {
                if (this.selectedCandidateIndex === null) return;
                if (this.candidateName === '') {
                    alert('请为候选人命名');
                    return;
                }

                const selectedCandidate = this.recruitmentCandidates[this.selectedCandidateIndex];

                // 实际应使用axios向后端发送招募请求
                axios.post('/api/hr/sure', {
                    id: selectedCandidate.id,
                    name: this.candidateName
                },{
                    headers: { 'Authorization': 'Bearer ' + localStorage.getItem('jwt')}
                })
                  .then(response => {
                      selectedCandidate.name = this.candidateName;
                    // 处理响应
                      this.gameData.humanResources.push(selectedCandidate);
                      this.gameData.gold -= this.recruitCostIncrement[this.gameData.stage - 1];
                      this.closeRecruitmentModal();

                      alert(`成功招募 ${selectedCandidate.name}！`);
                  });
            },

            // 升级人力
            upgradeHuman(index) {
                const human = this.gameData.humanResources[index];

                if (this.gameData.gold < human.trainCost) return;
                if (human.level >= human.maxLevel) return;

                // 实际应使用axios向后端发送升级请求
                axios.post('/api/hr/levelUp', {},{
                    params: {
                        id: human.id
                    },
                    headers: { 'Authorization': 'Bearer ' + localStorage.getItem('jwt')}
                })
                  .then(response => {
                        // 处理响应
                      this.gameData.humanResources[index].level++;
                      this.gameData.gold -= human.trainCost;

                      alert(`${human.name} 升级成功！当前等级: ${this.gameData.humanResources[index].level}`);
                  });
            },

            // 事件名称映射
            mapEventName(eventStr) {
                switch (eventStr) {
                    case "DDoS": return "DDoS攻击";
                    case "SQL": return "SQL注入攻击";
                    case "XSS": return "XSS攻击";
                    case "attention": return "关注度提升";
                    case "hit": return "风口红利";
                    case "normal": return "无事件";
                    default: return eventStr;
                }
            },

            // 获取事件图标
            getEventIcon(eventStr) {
                switch (eventStr) {
                    case "DDoS": return "🛡️";
                    case "SQL": return "💉";
                    case "XSS": return "🔪";
                    case "attention": return "⭐";
                    case "hit": return "🚀";
                    default: return "";
                }
            },

            // 获取事件颜色
            getEventColor(eventStr) {
                switch (eventStr) {
                    case "DDoS": return "#ff6b6b";
                    case "SQL": return "#ff9e6b";
                    case "XSS": return "#ffca6b";
                    case "attention": return "#6bffb8";
                    case "hit": return "#6bcaff";
                    default: return "#b0b0b0";
                }
            },

            // 关闭回合结算悬浮窗
            closeTurnResultModal() {
                this.showTurnResultModal = false;
            },

            // 获取指定周期发生的事件
            getCycleEvents(cycleRank) {
                const events = [];
                for (let i = 0; i < this.turnResult.happenedRank.length; i++) {
                    if (this.turnResult.happenedRank[i] === cycleRank) {
                        events.push(this.turnResult.event[i]);
                    }
                }
                // 如果没有事件，添加"normal"
                if (events.length === 0) {
                    events.push("normal");
                }
                return events;
            },

            // 结束当前回合
            endTurn() {
                axios.post('/api/game/turn', {
                    publicityCost: this.promotionCost
                }, {
                    headers: { 'Authorization': `Bearer ${localStorage.getItem('jwt')}` }
                })
                    .then(response => {
                        // 保存回合数据
                        this.turnResult = response.data.data;
                        // 更新游戏数据
                        const newData = response.data.data.gameData;
                        this.gameData.gold = newData.gold;
                        this.gameData.actionPoint = newData.actionPoint;
                        this.gameData.reputation = newData.reputation;
                        this.gameData.traffic = newData.traffic;
                        this.gameData.avgConsumption = newData.avgConsumption;
                        this.gameData.turns += 1;
                        // 显示回合结果
                        this.showTurnResultModal = true;
                        // 重置宣发花费
                        this.promotionCost = 0;
                    })
                    .catch(error => {
                        console.error('结束回合失败:', error);
                        alert('结束回合失败，请重试');
                    });
            },

            // 打开指南悬浮窗
            openGuide() {
                this.showGuideModal = true;
            },

            // 关闭指南悬浮窗
            closeGuide() {
                this.showGuideModal = false;
            },

            // 滚动到指定章节
            scrollToSection(sectionId) {
                this.currentSection = sectionId;
                const element = document.getElementById(sectionId);
                if (element) {
                    element.scrollIntoView({ behavior: "smooth", block: "start" });
                }
            }
        }
    }).mount('#app');
</script>
</body>
</html>